package com.ph.shopping.facade.permission.service.impl;

import java.util.Date;
import java.util.List;

import com.ph.shopping.facade.permission.dto.UpdatePassDto;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ph.shopping.common.core.base.BaseService;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.core.exception.BizException;
import com.ph.shopping.common.util.page.PageBean;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.common.util.rsa.MD5;
import com.ph.shopping.facade.mapper.RoleMapper;
import com.ph.shopping.facade.mapper.UserMapper;
import com.ph.shopping.facade.mapper.UserRoleMapper;
import com.ph.shopping.facade.permission.dto.UpdateUserRoleDto;
import com.ph.shopping.facade.permission.dto.UserDto;
import com.ph.shopping.facade.permission.dto.UserRoleDto;
import com.ph.shopping.facade.permission.entity.Role;
import com.ph.shopping.facade.permission.entity.User;
import com.ph.shopping.facade.permission.entity.UserRole;
import com.ph.shopping.facade.permission.service.IUserService;
import com.ph.shopping.facade.permission.service.check.ParamsCheck;
import com.ph.shopping.facade.permission.service.constant.UserConstant;
import com.ph.shopping.facade.permission.vo.UserVo;

/**
 * @项目：phshopping-service-permission
 * @描述： 用户接口的实现类
 * @作者： Mr.zheng
 * @创建时间：2017-03-14
 * @Copyright @2017 by Mr.zheng
 */
@Component
@Service(version="1.0.0")
public class UserService extends BaseService implements IUserService{

    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    @Autowired
    UserMapper userMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    /**
     * 新增用户
     * @param dto
     * @return
     * @throws BizException
     */
    @Transactional(rollbackFor=Exception.class)
    @Override
    public Result addUser(UserRoleDto dto) throws BizException{
        try {
        	logger.info("新增用户入参，dto={}",JSON.toJSONString(dto));
        	Result result = getResult(ResultEnum.MEMBER_DATA_ERROR);
        	if (ParamsCheck.checkAddUser(dto)) {
            	//验证手机号是否存在
                if (null != userMapper.findUserByPhone(dto.getTelphone())) {
                    return getResult(ResultEnum.REGISTERED);
                }
                User user =new User();
                //参数转换
                paramsTranf(user, dto);
                //新增用戶
                userMapper.insertUseGeneratedKeys(user);
                Long userId = user.getId();
                //除了管理员类型的账号以外，需要默认分配角色
                if (dto.getRoleCode().intValue() != 1) {
                	addUserRole(dto.getRoleCode().byteValue(), userId);
                }
                result = getResult(ResultEnum.SUCCESS,userId);
        	}
        	logger.info("新增用户返回值，result={}",JSON.toJSONString(result));
            return result;
        } catch (Exception ex) {
            logger.error("新增用户异常，ex={}", ex);
            throw new BizException("新增用户异常");
        }
    }

    private void paramsTranf(User user, UserRoleDto dto){
    	user.setEmail(dto.getEmail());
        user.setTelphone(dto.getTelphone());
        user.setPassword(dto.getPassword());
        user.setIsable(new Byte("1"));
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
    }
    
    private void addUserRole(Byte roleCode, Long userId) {
    	//通过roleCode查询角色信息
    	Role role = new Role();
    	role.setRoleCode(roleCode);
    	List<Role> list = roleMapper.selectRoleBySelective(role);
    	Long roleId = null;
    	if (CollectionUtils.isNotEmpty(list)) {
    		roleId = list.get(0).getId();
    	}
    	UserRole userRole = new UserRole();
    	userRole.setRoleID(roleId);
    	userRole.setUserID(userId);
    	userRoleMapper.inserUserRole(userRole);
    }



    /**
     * 修改密码
     */
    @Transactional
    @Override
    public Result updatePassword(User user) throws BizException{
        try {
        	logger.info("修改密码入参,user={}",JSON.toJSONString(user));
            modifyUser(user);
            return getResult(ResultEnum.SUCCESS);
        } catch (Exception ex) {
            logger.error("修改密码异常，ex={}", ex);
            throw new BizException("修改密码异常");
        }
    }

    /**
     * 修改密码(后台首页)
     * @param updatePassDto
     * @return Result
     */
    @Transactional
    @Override
    public Result updatePass(UpdatePassDto updatePassDto) {
        Result result = getResult(ResultEnum.FAIL);
        try {
            logger.info("(后台)修改密码入参,updatePassDto={}",JSON.toJSONString(updatePassDto));
            User user = userMapper.selectByPrimaryKey(updatePassDto.getId());
            String oldPass = MD5.getMD5Str(updatePassDto.getPassword());
            String newPass = MD5.getMD5Str(updatePassDto.getNewPassword());
            if (user != null && StringUtils.isNotBlank(user.getPassword())
                    && user.getPassword().equals(oldPass)) {
                User mdyUser = new User();
                mdyUser.setId(updatePassDto.getId());
                mdyUser.setPassword(newPass);
                modifyUser(mdyUser);
                result = getResult(ResultEnum.SUCCESS);
            } else {
                result = getResult(ResultEnum.PASSWORD_ERROR);
            }

        } catch (Exception ex) {
            logger.error("(后台)修改密码入参，ex={}", ex);
        }
        logger.info("(后台)修改密码返回值,result={}",JSON.toJSONString(result));
        return result;
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @Transactional
    @Override
    public Result updateUser(User user) throws BizException{
        try {
        	logger.info("修改用户信息入参,user={}",JSON.toJSONString(user));
        	//判断手机号是否重复
            User queryUser = userMapper.findUserByPhone(user.getTelphone());
            if ( null != queryUser &&  !queryUser.getId().equals(user.getId())) {
                return getResult(ResultEnum.REGISTERED);
            }
            modifyUser(user);
            return getResult(ResultEnum.SUCCESS);
        } catch (Exception ex) {
            logger.error("修改用户信息异常，ex={}", ex);
            throw new BizException("修改用户信息异常");
        }
    }

    /**
     * 冻结或者启用用户
     * @param user
     * @return
     */
    @Transactional
    @Override
    public Result frozenOrEnableUser(User user) throws BizException {
    	try {
    		logger.info("冻结或者启用用户入参,user={}",JSON.toJSONString(user));
    		user.setUpdateTime(new Date());
	        userMapper.updateByPrimaryKeySelective(user);
	        return getResult(ResultEnum.SUCCESS);
		} catch (Exception e) {
			throw new BizException("冻结或者启用用户异常");
		}
       
    }

    /**
     * 修改用户信息
     * @param user
     */
    private void modifyUser(User user) {
    	if (StringUtils.isNotBlank(user.getPassword())) {
    		user.setPassword(user.getPassword());
    	}
        user.setUpdateTime(new Date());
        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 删除用户
     * @param user
     * @return
     */
    @Transactional
    @Override
    public Result deleteUser(User user) throws BizException{
        try {
        	logger.info("删除用户入参,user={}",JSON.toJSONString(user));
            userMapper.deleteByPrimaryKey(user);
            userRoleMapper.deleteRoleByUserID(user.getId());
            return getResult(ResultEnum.SUCCESS);
        } catch (Exception ex) {
            logger.error("删除用户异常，ex={}", ex);
            throw new BizException("删除用户异常");
        }
    }

    /**
     * 查询用户信息
     * @param user
     * @return
     */
    @Override
    public Result queryUser(User user) {
        return getResult(ResultEnum.SUCCESS,userMapper.selectByPrimaryKey(user));
    }

    /**
     * 分页查询用户信息
     * @param userDto
     * @return
     */
    public Result getUserList(PageBean page,UserDto userDto) {
    	PageHelper.startPage(page.getPageNum(), page.getPageSize());
    	List<UserVo>list = userMapper.getUserByPage(userDto);
    	PageInfo<UserVo>pageInfo=new PageInfo<>(list);
        return getResult(ResultEnum.SUCCESS,pageInfo.getList(),pageInfo.getTotal());
    }

    /**
     * 通过用户id查询用户对应的角色id
     * @param userId
     * @return
     */
    @Override
    public Result queryUserRoleByUserID(Long userId) {
        return getResult(ResultEnum.SUCCESS,userRoleMapper.selectUserRoleByUserID(userId));
    }

    /**
     * 修改用户角色
     * @param updateUserRoleDto
     * @return
     */
    @Transactional
    @Override
    public Result updateUserRole(UpdateUserRoleDto updateUserRoleDto) throws BizException{
    	try {
    		logger.info("修改用户对应的角色入参，updateUserRoleDto={}", JSON.toJSONString(updateUserRoleDto));
    		userRoleMapper.deleteRoleByUserID(updateUserRoleDto.getUserID());
            userRoleMapper.insertUserRole(updateUserRoleDto.getUserID(),updateUserRoleDto.getRoleIDs());
            return getResult(ResultEnum.SUCCESS);
    	} catch (Exception e) {
			logger.error("修改用户对应的角色异常，ex={}", e);
			throw new BizException("修改用户对应的角色异常");
		}
       
    }


    /**
     * 重置密码：
     * @param user
     * @return
     */
    @Transactional
	@Override
	public Result resetPassword(User user) throws BizException{
		try {
			logger.info("重置密码入参，user={}", JSON.toJSONString(user));
			user.setPassword(MD5.getMD5Str(UserConstant.PASSWORD));
	        user.setUpdateTime(new Date());
	        userMapper.updateByPrimaryKeySelective(user);
			return getResult(ResultEnum.PASSWORD_REMIND);
		} catch (Exception e) {
			throw new BizException("重置密码异常");
		}
	 	
	}
}
